﻿using ClosedXML.Excel;
using DocumentFormat.OpenXml.Wordprocessing;
using DongFangGuoKai.WMSPlatform.Commn.TokenModule;
using DongFangGuoKai.WMSPlatform.Domain.Model;
using DongFangGuoKai.WMSPlatform.Service.BasicApp.Cell;
using DongFangGuoKai.WMSPlatform.Service.BasicApp.Cell.DTO;
using DongFangGuoKai.WMSPlatform.Service.BasicApp.Pallet;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using Newtonsoft.Json;
using System.Data;
using System.Text;

namespace DongFangGuoKai.WMSPlatform.WebApi.Controllers.BasicData
{
    /// <summary>
    /// 仓位管理
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class TCellController : BaseController
    {
        private readonly ICellService cellService;
        private readonly IConfiguration configuration;

        public TCellController(ICellService cellService, IConfiguration configuration)
        {
            this.cellService = cellService;
            this.configuration = configuration;
        }

        /// <summary>
        /// 列表显示
        /// </summary>
        /// <param name="logicalPartCode"></param>
        /// <param name="fullStatus"></param>
        /// <param name="status"></param>
        /// <param name="cname"></param>
        /// <param name="whid"></param>
        /// <param name="areid"></param>
        /// <param name="sheid"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetCellList(string? logicalPartCode = "", int fullStatus = 3, int status = 8, string? cname = "", int whid = 0, int areid = 0, int sheid = 0, int pageIndex = 1, int pageSize = 10)
        {
            if (pageIndex <= 0 || pageSize <= 0)
            {
                return Failed("分页条件有误！");
            }
            int totalCount;
            var list = cellService.GetCellList(logicalPartCode, fullStatus, status, cname, whid, areid, sheid, pageIndex, pageSize, out totalCount);

            if (list != null)
            {
                return Success(list, totalCount, "查询成功！");
            }
            return Failed( "查询失败！");
        }

        /// <summary>
        /// 更新仓位
        /// </summary>
        /// <param name="storeLocationCode"></param>
        /// <returns></returns>
        [HttpPut]
        public async Task<IActionResult> UpdCell()
        {
            string hnBaseUrl = configuration["HNBaseUrl"];
            var token = await TokenHelper.GetToken(hnBaseUrl);
            using var client = new HttpClient();
            client.DefaultRequestHeaders.Add("Authorization", token);
            // 发送GET请求
            HttpResponseMessage response = await client.GetAsync(hnBaseUrl + "/railway/pda/store/location/list");
            // 检查请求是否成功
            if (response.IsSuccessStatusCode)
            {
                var res = await response.Content.ReadAsStringAsync();
                var responseObject = JsonConvert.DeserializeObject<LocationListDTO>(res);

                if (responseObject is null)
                {
                    return Failed("查询失败");
                }

                var cellList = cellService.GetAllCellList();
                var delRes = cellService.DelCellList(cellList);
                if (!delRes)
                {
                    return Failed("更新失败");
                }
                List<TCells> cells = new List<TCells>();
                foreach (var item in responseObject.data)
                {
                    var cell = new TCells()
                    {
                        Code = item.storeLocationCode,
                        WhId = item.storeId,
                        CreateDate = DateTime.Now,
                        Erpcode = item.storeLocationId.ToString(),
                        Name = item.remark,
                        Status = 1
                    };
                    cells.Add(cell);
                }
                if (!cellService.AddCellList(cells))
                {
                    return Failed("更新失败");
                }
                return Success("更新成功");
            }
            else
            {
                return Failed("请求失败");
            }
        }


        /// <summary>
        /// 生成Excel表格数据
        /// </summary>
        /// <param name="logicalPartCode"></param>
        /// <param name="fullStatus"></param>
        /// <param name="status"></param>
        /// <param name="cname"></param>
        /// <param name="whid"></param>
        /// <param name="areid"></param>
        /// <param name="sheid"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult CelltExcelData(string? logicalPartCode = "", int fullStatus = 3, int status = 8, string? cname = "", int whid = 0, int areid = 0, int sheid = 0, int pageIndex = 1, int pageSize = 10)
        {
            if (pageIndex <= 0 || pageSize <= 0)
            {
                return Failed("分页条件有误！", 400);
            }
             int totalCount;
            var list = cellService.GetCellList(logicalPartCode, fullStatus, status, cname, whid, areid, sheid, pageIndex, pageSize, out totalCount);
            if (list == null)
            {
                return Failed("查询失败！");
            }
            DataTable dt = new DataTable();
            dt.Columns.Add("货架名称");
            dt.Columns.Add("货架编码");
            dt.Columns.Add("字节值");
            foreach (var item in list)
            {
                var byteArray = Encoding.UTF8.GetBytes(item.Code);
                string hexString = BitConverter.ToString(byteArray).Replace("-", "");
                dt.Rows.Add(item.Name, item.Code, hexString);
            }
            using (var workbook = new XLWorkbook())
            {
                // 将DataTable添加到工作表中
                var worksheet = workbook.Worksheets.Add("Sheet1");
                worksheet.Cell(1, 1).InsertTable(dt);

                // 保存到指定路径
                workbook.SaveAs("SampleData.xlsx");
            }

            return Success(list, totalCount, "查询成功！");
        }
    }
}
